<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\Goods as ProductModel;
use addons\kuerp\model\GoodsType;
use think\Db;
use think\Exception;

/**
 * 产品
 */
class Goods extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = ['getUnit'];


	//获取产品记录
	public function getList() {
		$limit  = input("limit/d", 10);
		$params = $this->request->post();
		$where  = [];
        $where['status'] = ['=',1];
		$order  = 'id desc';
		if (isset($params['name']) && $params['name']) {//产品名称
			$where['goods_name|goods_code'] = ['like', "%{$params['name']}%"];
		}

		if (isset($params['type_id']) && $params['type_id']) {//产品名称
            $typeids=GoodsType::where(['pid'=>$params['type_id']])->whereOr(['id'=>$params['type_id']])->column('id');
			$where['goods_type_id'] = ['in',$typeids];
		}

		$list              = ProductModel::where($where)->field('description',true)->order($order)->paginate($limit);
		if ($list) {
			$list = $list->toArray();
			$unitids = array_column($list['data'], 'unit_id');
			$unit_list = Db::name('kuerp_unit')->where(['id' => ['in', $unitids]])->column('id,name');
			$default_img = cdnurl(config('site.default_goods_img'), true);
			//销售人员 显示库存 锁号
			$stocks = [];
			$goods_ids = array_column($list['data'], 'id');
			if ($this->auth->is_sale && $this->auth->stores_info) {
				$stocks = Db::name('kuerp_goods_stock')->where(['goods_id' => ['in', $goods_ids], 'stores_id' => $this->auth->stores_info['id']])->column('stock', 'goods_id');
			}
			$list['data'] = array_map(function ($v) use ($unit_list, $default_img, $stocks) {
				$v['unit'] = $unit_list[$v['unit_id']];
				$v['goods_image'] = $v['goods_image'] ? cdnurl($v['goods_image'], true) : $default_img;
				$v['stock'] = !empty($stocks[$v['id']]) ? $stocks[$v['id']] : $v['inventory'];
				$v['stock'] = $v['stock'] < 0 ? 0 : $v['stock'];
				return $v;
			}, $list['data']);
		}
		$this->success('请求成功', $list);
	}


	//获取select产品列表
	public function getSelectList() {
		$name  = input('name');
		$where = [];
		if ($name) {
			$where['goods_name|goods_code'] = ['like', "%{$name}%"];
		}
        if (isset($params['type_id']) && $params['type_id']) {//产品名称
            $typeids=GoodsType::where(['pid'=>$params['type_id']])->column('id');
            $where['goods_type_id'] = ['in',$typeids];
        }

		$list              = ProductModel::where($where)->select();
		$this->success('请求成功', $list);
	}


	//添加产品
	public function addProduct() {
		$params = $this->request->post();
		// 表单验证
		if (($result = $this->kuerpValidate($params,get_class(), 'create')) !== true) {
			$this->error($result);
		}
		if (ProductModel::where(['goods_name' => $params['name']])->find()) {
			$this->error('产品名称已存在');
		}

		try {
			$product            = ProductModel::createProduct($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('新增产品成功');
		}
	}


	//修改产品
	public function editProduct() {
		$id     = input('id');
		$params = $this->request->post();
		$row    = ProductModel::where(['id' => $id])->find();
		if (empty($row)) {
			$this->error('修改产品信息不存在');
		}
		// 表单验证
		if (($result = $this->kuerpValidate($params,get_class(), 'edit')) !== true) {
			$this->error($result);
		}
		Db::startTrans();
		try {
			$result = ProductModel::updateProduct($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		$this->success('修改产品信息成功');
	}


	//获取产品详情
	public function getProductDetail(){
	    $id=input('id');
	    $product=ProductModel::where(['id'=>$id])->find();
	    if(empty($product)){
	        $this->error('产品信息不存在');
        }
		if ($this->auth->is_sale && $this->auth->stores_info) {
			$product['stock'] = (float)Db::name('kuerp_goods_stock')->where(['goods_id' => $id, 'stores_id' => $this->auth->stores_info['id']])->value('stock');
			$product['stock'] = $product['stock'] < 0 ? 0 : $product['stock'];
		} else {
			$product['stock'] = $product['inventory'];
		}
		$product['serial_list'] = null;
		if ($product['serial']) {
			$serial_where = [
				'goods_id' => $product['id'],
				'store_status' => 1
			];
			if ($this->auth->is_sale && $this->auth->stores_info) {
				$serial_where['stores_id'] = $this->auth->stores_info['id'];
			}
			$product['serial_list'] = Db::name('kuerp_goods_serial')->where($serial_where)->column('serial,remark');
		}
		$product['unit'] = $product['unit_id'] ? Db::name('kuerp_unit')->where(['id' => $product['unit_id']])->value('name') : '';
		$default_img = cdnurl(config('site.default_goods_img'), true);
		$product['goods_image'] = $product['goods_image'] ? cdnurl($product['goods_image'], true) : $default_img;
	    $this->success('请求成功',$product);
    }


    //获取产品分类
    public function getProductType(){
       $types= GoodsType::where(['pid'=>0])->field('id,supplier_type_name as name')->select();
        $this->success('请求成功',$types);
    }
//获取select商品列表
    public function getGoodsList()
    {
        $limit = input("limit/d", 10);
        $name = input('name');
        $type_id = input('type_id');
        $where = [];
        if ($name) {
            $where['name|num'] = ['like', "%{$name}%"];
        }
        if ($type_id) {
            $where['type_id'] = $type_id;
        }
        $list = Goods::with(['type','specs'])->where($where)->paginate($limit);
        foreach ($list as $k=>$v) {
            $list[$k]['image'] = cdnurl($v['image'], true);

        }
        $this->success('请求成功', $list);
    }

	//获取单位价格信息
    public function getUnit($goods_code='',$store='',$attr='',$supplyer_code=''){
        $set= Db::name('kuerp_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();
        $taxes= Db::name('kuerp_sets')->where(['name'=>'price_taxes'])->value('is_checked');

        if($goods_code){
            $row = Db::name('kuerp_goods')->where(['goods_code'=>$goods_code])->field('batch,serial,id,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,batch,shelf_life,warehousing,warehouse')->find();
            $goods_id = isset($row['id'])?$row['id']:0;
        }else{
            $goods_id = isset($_POST['goods_id'])?$_POST['goods_id']:0;
            $row = Db::name('kuerp_goods')->where(['id'=>$goods_id])->field('batch,serial,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,batch,shelf_life,warehousing,warehouse')->find();
        }
        if(empty($row)){
            return [];
        }
        if($supplyer_code){
            $suppliers = Db::name('kuerp_suppliers')->where(['supplyer_code'=>$supplyer_code])->value('vat_rate');
        }

        $auxiliary = Db::name('kuerp_auxiliary')->where(['status'=>1])->column('name','id');
        $goods_attr = Db::name('kuerp_goods_attr')->where(['goods_id'=>$goods_id])->select();
        foreach ($goods_attr as $goods_attr_k=>$goods_attr_v){
            $aux_combination = Db::name('kuerp_aux_combination')->where(['id'=>$goods_attr_v['attribute_id']])->value('attr_ids');
            $goods_attr[$goods_attr_k]['attr_ids'] = [];
            $goods_attr[$goods_attr_k]['attr_name'] = '';
            if($aux_combination){
                $goods_attr[$goods_attr_k]['attr_id'] = $aux_combination;
                $aux_combination = explode('&',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_ids'] = $aux_combination;
                foreach ($aux_combination as $aux_combination_k=>$aux_combination_v){
                    $aux_combination[$aux_combination_k] = isset($auxiliary[$aux_combination_v])?$auxiliary[$aux_combination_v]:'';
                }
                $aux_combination = implode('/',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_name'] = $aux_combination;
            }
        }


        $where = [];
        $where['goods_id'] = $goods_id;
        if($store){
            $where['stores_id'] = $store;
        }else{
            $where['stores_id'] = $row['manager_warehouse_id'];
        }
        if($attr){
            //$attribute_id = Db::name('kuerp_goods_attr')->where(['goods_id'=>$goods_id,'id'=>$attr])->value('attribute_id');
            $where['attribute_id'] = $attr;
        }
        $stock = Db::name('kuerp_goods_stock')->where($where)->value('stock');
        if($row['more_unit']==1){
            $unit = Db::name('kuerp_unit_conversion')->alias('uc')
                ->join('kuerp_unit u','u.id=uc.vice_unit')
                ->where(['uc.main_unit'=>$row['unit_id']])
                ->order('uc.advance_rate','ASC')
                ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                ->select();
            $unit_ids = [$row['unit_id']];
            foreach ($unit as $unit_k=>$unit_v){
                $unit_ids[] = $unit_v['id'];
            }
            $goods_price = Db::name('kuerp_goods_price')->where(['unit'=>['in',$unit_ids],'goods_id'=>$goods_id])->select();
            foreach ($goods_price as $goods_price_k=>$goods_price_v){
                foreach ($unit as $unit_k=>$unit_v){
                    if($goods_price_v['unit']==$row['unit_id']){
                        $goods_price[$goods_price_k]['advance_rate'] = 1;
                    }else if($goods_price_v['unit']==$unit_v['id']){
                        $goods_price[$goods_price_k]['advance_rate'] = $unit_v['advance_rate'];
                    }
                }
            }
        }else{
            $unit_ids = [$row['unit_id']];
        }
        $unit = Db::name('kuerp_unit')->where(['id'=>['in',$unit_ids]])->field('id,name')->select();
        foreach ($unit as $unit_k=>$unit_v){
            if(isset($goods_price)){
                foreach ($goods_price as $goods_price_k=>$goods_price_v){
                    if($unit_v['id']==$goods_price_v['unit']){
                        $unit[$unit_k]['is_default'] = $goods_price_v['is_default'];
                        //$unit[$unit_k]['purchase'] = $goods_price_v['purchase']*$goods_price_v['advance_rate'];
                        $unit[$unit_k]['purchase'] = $goods_price_v['purchase'];
                        if($goods_price_v['is_default']!=1){
                            $unit[$unit_k]['basic_nmber'] = $goods_price_v['advance_rate'];
                        }else{
                            $unit[$unit_k]['basic_nmber'] = 1;
                        }
                    }
                }
            }else{
                if($row['auxiliary']==1 && !empty($attr)){
                    $purchase = Db::name('kuerp_goods_attr')->where(['goods_id'=>$goods_id,'id'=>$attr])->value('purchase');
                }else{
                    $purchase = $row['purchase'];
                }
                if($unit_v['id']==$row['unit_id']){
                    $unit[$unit_k]['is_default'] = 1;
                    $unit[$unit_k]['basic_nmber'] = 1;
                    $unit[$unit_k]['purchase'] = $purchase;
                }
            }
        }
        foreach ($unit as $unit_k=>$unit_v){
            if(isset($suppliers) && $suppliers!==''){
                $tax = $suppliers;
            }else{
                $tax = $set['value'];
            }
            if(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1){
                $unit[$unit_k]['tax'] = 1;
                $unit[$unit_k]['tax_rate'] = $tax;
            }else{
                $unit[$unit_k]['tax'] = 0;
                $unit[$unit_k]['tax_rate'] = 0;
            }
            if(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1 && $taxes==1){
                $unit[$unit_k]['purchase'] = round(($unit_v['purchase']/(100+$tax)*100),4);
                $unit[$unit_k]['tax_included'] = $unit_v['purchase'];
            }elseif(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1 && $taxes!=1){
                $unit[$unit_k]['purchase'] = $unit_v['purchase'];
                $unit[$unit_k]['tax_included'] = round(($unit_v['purchase']*(100+$tax)/100),4);
            }else{
                $unit[$unit_k]['purchase'] = $unit_v['purchase'];
                $unit[$unit_k]['tax_included'] = $unit_v['purchase'];
            }
        }
        $data = [];
        foreach ($unit_ids as $unit_ids_k=>$unit_ids_v){
            foreach ($unit as $unit_k=>$unit_v){
                if($unit_ids_v==$unit_v['id']){
                    if($unit_v['is_default']==1){
                        $unit_v['stock'] = is_null($stock)?0:$stock;
                    }else{
                        $unit_v['stock'] = round($stock/$unit_v['basic_nmber'],2);
                    }
                    $unit_v['tax_money'] = round(($unit_v['tax_included']-$unit_v['purchase']),4);;
                    $data[] = $unit_v;
                }
            }
        }
        return json_encode(['unit'=>$data,'attr'=>$goods_attr,'goods'=>$row]);
    }

}
